<template>
  <div style="width: 100%;height: 100%;">
    <el-card style="height: 80px;">
      <div style="overflow: hidden;height: 100%;">
        <h3 style="float: left;">添加演员信息</h3>
        <el-button type="primary"
                   style="width: 150px;height: 40px;
                   float: right;margin-top: 20px"
                   @click="add"
        >添加
        </el-button>
      </div>
    </el-card>
    <el-card style="height:650px;">
      <el-empty v-if="tableData.length === 0"
                style="height: 650px;"
                description="没有数据"/>
      <el-scrollbar height="650">
      <div style="height: 650px;width: 98%;text-align: center;">
          <el-row :gutter="10">
            <el-col :span="4" v-for="item in tableData">
              <el-card style="margin-top: 5px; border-radius: 10px;height: 240px;">
                <el-avatar style="width: 100px; height: 100px">
                  <el-image :src="BASE_URL + item.poster" alt="Actor poster"
                            style="height: 100px"/>
                </el-avatar>
                <p style="font-size: 16px">{{ item.actorName }}</p>
                <p style="font-size: 14px;">{{ item.participation }} {{ item.role }}</p>
                <el-button type="primary" size="small"
                           @click="editFilmActor(item.id)">编辑
                </el-button>
                <el-button type="danger" size="small"
                           @click="deleteFilmActor(item.id)">删除
                </el-button>

              </el-card>
            </el-col>
          </el-row>
      </div>
      </el-scrollbar>
    </el-card>

    <el-dialog v-model="actorVisible"
               :title="actorTitle"
               width="40%"
               :before-close="handleCloseFilmActor"
               style="padding: 40px;margin-top: 200px;">
      <el-form ref="form"  label-width="100px">
        <el-form-item label="演员姓名">
          <el-select
              v-model="saveFilmActorParam.actorId"
              clearable
              filterable
              style="width:330px;"
              placeholder="请输入演员姓名">
            <el-option
                v-for="item in actorData"
                :key="item.value"
                :label="item.name"
                :value="item.id">
            </el-option>
            <template #footer>
              <el-button type="primary" link
                         @click="addActor">添加未保存演员信息</el-button>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="saveFilmActorParam.participation"
                     style="width:100px;"
                     placeholder="请选择参与方式">
            <el-option label="饰演" value="饰演"/>
            <el-option label="配音" value="配音"/>
          </el-select>
          <el-input v-model="saveFilmActorParam.role" style="width:220px;margin-left: 10px"
                    placeholder="请输入演员角色"/>
        </el-form-item>
        <el-form-item label="排序">
          <el-input v-model="saveFilmActorParam.sort" style="width:330px;"
                    placeholder="请输入排序序号"/>
        </el-form-item>
      </el-form>
       <template #footer>
         <el-button type="danger" @click="handleCloseFilmActor">取消</el-button>
         <el-button type="primary" @click="saveFilmActor">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="saveActorTitle"
               v-model="saveActorVisible"
               style="width:800px; padding:40px;"
               :before-close="saveHandleClose">
      <el-form label-width="80px" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="演员姓名">
              <el-input placeholder="请输入演员姓名"
                        v-model="saveActorFrom.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="演员英文名">
              <el-input placeholder="请输入演员英文名"
                        v-model="saveActorFrom.englishName"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="演员国籍">
              <el-select v-model="saveActorFrom.nationality"
                         placeholder="请选择演员国籍">
                <el-option
                    v-for="item in nationalityList"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="演员照片">
              <el-upload
                  v-model:file-list="fileList"
                  v-model:action="actionUrl"
                  name="file"
                  limit="1"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img :src="dialogImageUrl"
                     :alt="dialogImageUrl"/>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="danger" @click="saveHandleClose">取消</el-button>
        <el-button type="primary" @click="saveActor">保存</el-button>
      </template>
    </el-dialog>
    <el-button type="success"
               @click="success"
               style="position: absolute;
                   top: 90%;right: 85px;">
      完成
    </el-button>
    <el-button
        style="position: absolute;top: 90%;right: 15px;"
        @click="cancel"
        type="danger">
      取消
    </el-button>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";
import router from "@/router";

let filmId = new URLSearchParams(window.location.search).get('id');
const nationalityList = ref([]);
onMounted(() => {
  loadDictOptions(nationalityList, 'nationality');
});
const tableData = ref([]);
const selectFilmActor = () => {
  axios.get(BASE_URL + '/v1/filmActor/select/' + filmId)
      .then(response => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};
// 测试添加
onMounted(() => {
  selectFilmActor();
  searchActor();
})
const actorData = ref([]);
const searchActor = () => {
  axios.get(BASE_URL + '/v1/actor/select?')
      .then((response) => {
        if (response.data.code === 2000) {
          actorData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}

const saveActorVisible = ref(false);
const saveActorTitle = ref('新增演员');
const saveActorFrom = ref({
  name: '',
  englishName: '',
  nationality: '',
  poster: '',
});
const cleanAll = () => {
  saveActorFrom.value = {
    name: '',
    englishName: '',
    nationality: '',
    poster: '',
  };
  fileList.value = [];
}
/**图片上传相关代码开始**/
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true;
  console.log(uploadFile);
  //console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/

const addActor = () => {
  saveActorVisible.value = true;
  saveActorTitle.value = '新增导演';
}

const saveActor = () => {

  if (saveActorFrom.value.name===null || saveActorFrom.value.name===''){
    errorInfo('请输入演员姓名');
    return;
  }
  if (saveActorFrom.value.nationality===null || saveActorFrom.value.nationality===''){
    errorInfo('请选择演员国籍');
    return;
  }

  if (fileList.value.length === 0) {
    errorInfo('请上传演员海报');
    return;
  }

  saveActorFrom.value.poster = fileList.value[0].response.data;
  let data = qs.stringify(saveActorFrom.value);
  axios.post(BASE_URL + '/v1/actor/save', data)
      .then((response) => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          saveActorVisible.value = false;
          cleanAll();
          searchActor();
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          })
        }
      })

}
const saveHandleClose = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    cleanAll();
    saveActorVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}

const saveFilmActorParam = ref({
  filmId: filmId,
  actorId: '',
  participation: '',
  role: '',
  sort: ''
});
const actorVisible = ref(false);
const actorTitle = ref('添加电影演员信息');
const add = () => {
  actorVisible.value = true;
  actorTitle.value = '添加电影演员信息';
};
const saveFilmActor = () => {
  if (saveFilmActorParam.value.actorId === null || saveFilmActorParam.value.actorId === '') {
    errorInfo('请选择演员');
    return;
  }
  if (saveFilmActorParam.value.participation === null || saveFilmActorParam.value.participation === '') {
    errorInfo('请选择角色');
    return;
  }
  if (saveFilmActorParam.value.role === null || saveFilmActorParam.value.role === '') {
    errorInfo('请输入饰演角色');
    return;
  }
  let data = qs.stringify(saveFilmActorParam.value);
  axios.post(BASE_URL + '/v1/filmActor/save', data).then((response) => {
    if (response.data.code === 2000) {
      OKInfo('保存成功!');
      selectFilmActor();
      actorVisible.value = false;
      saveFilmActorParam.value = {
        filmId: filmId,
        actorId: '',
        participation: '',
        role: '',
        sort: ''
      };
    } else {
      ElMessage({
        message: response.data.msg,
        type: 'error',
        showClose: true,
        center: true,
      })
    }
})
};

const handleCloseFilmActor = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    saveFilmActorParam.value = {
      filmId: filmId,
      actorId: '',
      participation: '',
      role: '',
      sort: ''
    };
    actorVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}
const editFilmActor = (id) => {
  actorVisible.value = true;
  actorTitle.value = '编辑电影演员信息';
  axios.get(BASE_URL + '/v1/filmActor/select/selectById/' + id)
      .then((response) => {
    if (response.data.code === 2000) {
      saveFilmActorParam.value = response.data.data[0];
    } else {
      ElMessage({
        message: response.data.msg,
        type: 'error',
        showClose: true,
        center: true,
      });
    }
  });
}

const deleteFilmActor = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/filmActor/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000){
            OKInfo('删除成功!');
            selectFilmActor();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {
    //取消没有操作
  })
}

const success = () => {
  router.push('/success')
}

const cancel = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/filmActor/delete/film/' + filmId)
        .then((response) => {
          if (response.data.code === 2000){
            OKInfo('已取消保存!');
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  saveActorFrom.value = {};
  router.push('/film')
  }).catch(() => {
    //取消没有操作
  });
}
window.addEventListener('beforeunload', function (e) {
  var message = "您确定要离开此页面吗？未保存的数据可能会丢失。";
  e.returnValue = message;
  return message;
});
</script>

<style scoped>
p {
  margin: 10px;
}
</style>